package com.summer.shopping.service.fun.impl;

import com.summer.shopping.enums.redis.RedisKeyConstant;
import com.summer.shopping.event.checkin.CheckinEvent;
import com.summer.shopping.service.fun.CampaignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class CampaignServiceImpl implements CampaignService {


    @Autowired
    ApplicationEventPublisher publisher;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public String checkInCampaign(Long userId) {
        String key = RedisKeyConstant.checkinKey(new Date());
        if (isCheckIn(userId)) {
            return "今天已经签到过了, 请不要重复签到";
        }
        stringRedisTemplate.opsForValue().setBit(key, userId, true);
        publisher.publishEvent(CheckinEvent.quickGet(userId));
        return "签到成功";
    }

    @Override
    public Boolean isCheckIn(Long userId) {
        String key = RedisKeyConstant.checkinKey(new Date());
        return Boolean.TRUE.equals(stringRedisTemplate.opsForValue().getBit(key, userId));
    }


}
